<?php
Zend_Loader::loadClass("Application_Ajax_Server_Function");
Zend_Loader::loadClass('Runs');
Zend_Loader::loadClass('Simulations');
Zend_Loader::loadClass('Sites');
Zend_Loader::loadClass('Buildings');
Zend_Loader::loadClass('Zones');

class SaveSimulation extends Application_Ajax_Server_Function
{
	public function call() {
		
		foreach ($this->_params as &$param) {
			//echo "\n<br>decoding" . print_r($param, 1);
			$param = deep_urldecode($param);
		}
		$simulazioni = new Simulations();
		$runs = new Runs();
		switch ($this->_getParam('part')) {
			case 'verify':
				$sim = $simulazioni->fetchRow($simulazioni->select()->where('sim_hash = ?', $this->_getParam('sim_hash')));
				$run = $sim ? $sim->findDependentRowset($runs) : null;
                return array ("sim_exists" => !is_null($sim), 'run_exists' => !is_null($run) && ($run->current()->run_status != Runs::SIMULATION_READY));
				break;
			case 'summary':
				if (!$this->_getParam('sim_hash') || !$this->_getParam('sim_name') || $this->_getParam('sim_hash') != md5($this->_getParam('sim_name'))) {
					return false;
				}

				// Oggetto simulazione
				$sim = $simulazioni->fetchRow($simulazioni->select()->where('sim_hash = ?', $this->_getParam('sim_hash')));
				if (!$sim || $this->_getParam('sim_save_as')) {
					$sim = $simulazioni->createRow();
				}
				
				$sim->sim_name = $this->_getParam('sim_name', 'Nuova simulazione');
				$sim->sim_hash = md5($sim->sim_name);
				$sim->sim_descr = $this->_getParam('sim_descr', '');
				$sim->sim_timestep = $this->_getParam('sim_timestep');
				$sim->sim_solar_distr = $this->_getParam('sim_solar_distr');
				$sim->sim_shadow_period = $this->_getParam('sim_shadow_period');
				$sim->sim_shadow_alg = $this->_getParam('sim_shadow_alg');
				$sim->sim_start = $this->_getParam('sim_start');
				$sim->sim_end = $this->_getParam('sim_end');
				$sim->sim_submit_date = $this->_getParam('submit_date', date('Y-m-d H:i:s'));
				$sim->save();

                $select = $runs->select();
                $select->where("id_simulation = ?", $sim->id);
                $run = $runs->fetchRow($select);
                if (!$run) {
                    $run = $runs->createRow(array(
                        'id_simulation' => $sim->id,
                        'run_date'      => date("Y-m-d H:i:s"),
                        'run_status'    => Runs::SIMULATION_READY
                    ));
                    $run->save();
                }

				break;
			case 'site':
				if (!$this->_getParam('sim_hash')) {
					return false;
				}
				// Rif. simulazione
				$sim = $simulazioni->fetchRow($simulazioni->select()->where('sim_hash = ?', $this->_getParam('sim_hash')));
				if (!$sim) {
					return false;
				}
				// Oggetto sito
				$sites = new Sites();
				$simSites = $sim->findDependentRowset('Sites');
				$site = $simSites->offsetExists(0) ? $simSites->offsetGet(0) : $sites->createRow();
				$site->id_simulation = $sim->id;
				$site->id_weather = null;
				$site->geo_lat = $this->_getParam('geo_lat', 0.0);
				$site->geo_lng = $this->_getParam('geo_lng', 0.0);
				$site->geo_north = $this->_getParam('geo_north', 0);
				$site->geo_elevation = $this->_getParam('geo_elevation', 0);
				$site->geo_terrain = $this->_getParam('geo_terrain');
				$site->terrain_reflection_sun = $this->_getParam('terrain_reflection_sun', 0.0);
				$site->terrain_reflection_snow = $this->_getParam('terrain_reflection_snow', 0.0);
				$site->terrain_reflection_ssnow = $this->_getParam('terrain_reflection_ssnow', 0.0);
				$site->terrain_temps = serialize($this->_getParam('terrain_temps'));
				$site->rain_design_yearly = $this->_getParam('rain_design_yearly', 0.0);
				$site->rain_nominal_yearly = $this->_getParam('rain_nominal_yearly', 0.0);
				$site->rain_schedule = $this->_getParam('rain_schedule', '');
				$site->tz_timezone = $this->_getParam('tz_timezone', 0);
				$site->tz_winter_start = $this->_getParam('tz_winter_start', '');
				$site->tz_winter_end = $this->_getParam('tz_winter_end', '');
				$site->tz_summer_start = $this->_getParam('tz_summer_start', '');
				$site->tz_summer_end = $this->_getParam('tz_summer_end', '');
				
				$site->save();
				break;
			case 'building':
				if (!$this->_getParam('sim_hash')) {
					return false;
				}
				// Rif. simulazione
				$sim = $simulazioni->fetchRow($simulazioni->select()->where('sim_hash = ?', $this->_getParam('sim_hash')));
				if (!$sim) {
					return false;
				}
				// Oggetto building
				$buildings = new Buildings();
				$simBuildings = $sim->findDependentRowset('Buildings');
				$building = $simBuildings->offsetExists(0) ? $simBuildings->offsetGet(0) : $buildings->createRow();
				$building->id_simulation = $sim->id;
				$building->project_sector = $this->_getParam('project_sector');
				$building->project_name = $this->_getParam('project_name');
				$building->project_address = $this->_getParam('project_address');
				$building->project_city = $this->_getParam('project_city');
				$building->project_zip = $this->_getParam('project_zip');
				$building->engineer_name = $this->_getParam('engineer_name');
				$building->engineer_phone = $this->_getParam('engineer_phone');
				$building->engineer_address = $this->_getParam('engineer_address');
				$building->engineer_city = $this->_getParam('engineer_city');
				$building->engineer_zip = $this->_getParam('engineer_zip');
				$building->owner_name = $this->_getParam('owner_name');
				$building->owner_phone = $this->_getParam('owner_phone');
				$building->owner_address = $this->_getParam('owner_address');
				$building->owner_city = $this->_getParam('owner_city');
				$building->owner_zip = $this->_getParam('owner_zip');
				
				$building->save();
				break;
			case 'zone':
				if (!$this->_getParam('sim_hash')) {
					return false;
				}
				// Rif. simulazione
				$sim = $simulazioni->fetchRow($simulazioni->select()->where('sim_hash = ?', $this->_getParam('sim_hash')));
				if (!$sim) {
					return false;
				}
				// Oggetto zone
				$zones = new Zones();
				$simZones = $sim->findDependentRowset('Zones');
				$zone = $simZones->offsetExists(0) ? $simZones->offsetGet(0) : $zones->createRow();
				$zone->id_simulation = $sim->id;
				$zone->geometry_length = $this->_getParam('geometry_length', 0.0);
				$zone->geometry_depth = $this->_getParam('geometry_depth', 0.0);
				$zone->geometry_height = $this->_getParam('geometry_height', 0.0);
				$zone->geometry_storey = $this->_getParam('geometry_storey');
				
				$zone->boundaries = serialize(array(
					'N' => $this->_getParam('wall_north_status'),
					'E' => $this->_getParam('wall_east_status'),
					'S' => $this->_getParam('wall_south_status'),
					'W' => $this->_getParam('wall_west_status')
				));
				
				$zone->walls = serialize(array(
					'N' => $this->_getParam('wall_north_id'),
					'E' => $this->_getParam('wall_east_id'),
					'S' => $this->_getParam('wall_south_id'),
					'W' => $this->_getParam('wall_west_id')
				));
				
				$zone->doors = serialize(array(
					'N' => array(
						'door_north_id' => $this->_getParam('door_north_id'),
						'door_north_length' => $this->_getParam('door_north_length'),
						'door_north_height' => $this->_getParam('door_north_height'),
						'door_north_elev' => $this->_getParam('door_north_elev', 0),
						'door_north_num' => $this->_getParam('door_north_num'),
					),
					'E' => array(
						'door_east_id' => $this->_getParam('door_east_id'),
						'door_east_length' => $this->_getParam('door_east_length'),
						'door_east_height' => $this->_getParam('door_east_height'),
						'door_east_elev' => $this->_getParam('door_east_elev', 0),
						'door_east_num' => $this->_getParam('door_east_num'),
					),
					'S' => array(
						'door_south_id' => $this->_getParam('door_south_id'),
						'door_south_length' => $this->_getParam('door_south_length'),
						'door_south_height' => $this->_getParam('door_south_height'),
						'door_south_elev' => $this->_getParam('door_south_elev', 0),
						'door_south_num' => $this->_getParam('door_south_num'),
					),
					'W' => array(
						'door_west_id' => $this->_getParam('door_west_id'),
						'door_west_length' => $this->_getParam('door_west_length'),
						'door_west_height' => $this->_getParam('door_west_height'),
						'door_west_elev' => $this->_getParam('door_west_elev', 0),
						'door_west_num' => $this->_getParam('door_west_num'),
					)
				));
				
				$zone->windows = serialize(array(
					'N' => array(
						'window_north_id' => $this->_getParam('window_north_id'),
						'window_north_length' => $this->_getParam('window_north_length'),
						'window_north_height' => $this->_getParam('window_north_height'),
						'window_north_elev' => $this->_getParam('window_north_elev'),
						'window_north_num' => $this->_getParam('window_north_num'),
					),
					'E' => array(
						'window_east_id' => $this->_getParam('window_east_id'),
						'window_east_length' => $this->_getParam('window_east_length'),
						'window_east_height' => $this->_getParam('window_east_height'),
						'window_east_elev' => $this->_getParam('window_east_elev'),
						'window_east_num' => $this->_getParam('window_east_num'),
					),
					'S' => array(
						'window_south_id' => $this->_getParam('window_south_id'),
						'window_south_length' => $this->_getParam('window_south_length'),
						'window_south_height' => $this->_getParam('window_south_height'),
						'window_south_elev' => $this->_getParam('window_south_elev'),
						'window_south_num' => $this->_getParam('window_south_num'),
					),
					'W' => array(
						'window_west_id' => $this->_getParam('window_west_id'),
						'window_west_length' => $this->_getParam('window_west_length'),
						'window_west_height' => $this->_getParam('window_west_height'),
						'window_west_elev' => $this->_getParam('window_west_elev'),
						'window_west_num' => $this->_getParam('window_west_num'),
					),
					'frame' => array(
						'frame_width' => $this->_getParam('frame_width'),
						'frame_outside' => $this->_getParam('frame_outside'),
						'frame_inside' => $this->_getParam('frame_inside'),
						'frame_conductance' => $this->_getParam('frame_conductance'),
						'frame_solar_absorptance' => $this->_getParam('frame_solar_absorptance'),
						'frame_visible_absorptance' => $this->_getParam('frame_visible_absorptance'),
						'frame_emissivity' => $this->_getParam('frame_emissivity'),
						'frame_divider' => $this->_getParam('frame_divider'),
						'frame_divider_width' => $this->_getParam('frame_divider_width'),
						'frame_divider_hnum' => $this->_getParam('frame_divider_hnum'),
						'frame_divider_vnum' => $this->_getParam('frame_divider_vnum'),
						'frame_divider_outside' => $this->_getParam('frame_divider_outside'),
						'frame_divider_inside' => $this->_getParam('frame_divider_inside'),
						'frame_divider_conductance' => $this->_getParam('frame_divider_conductance'),
						'frame_divider_solar_absorptance' => $this->_getParam('frame_divider_solar_absorptance'),
						'frame_divider_visible_absorptance' => $this->_getParam('frame_divider_visible_absorptance'),
					)
				));
				
				$zone->floors = serialize(array(
					'floor' => $this->_getParam('floor_id'),
					'ceiling' => $this->_getParam('ceiling_id')
				));
				
				$zone->save();
				break;
			default:
				return false;
		}
		return true;
		/*
		$esito = null;
		Model::getDefaultAdapter()->beginTransaction();
		$scenario = $this->_getParam('id', 0) ? "update" : "new";
		
		try {
			$materiali = new Materials();
			$materiale = ($scenario == "new") ? $materiali->createRow() : $materiali->fetchRow($materiali->select()->where('id = ?', $this->_getParam('id')));
			// materiale
			$materiale->name = $this->_getParam('material_name', '');
			$materiale->description = $this->_getParam('material_descr', '');
			$materiale->id_category = $this->_getParam('material_category_id', null);
			$materiale->thickness = $this->_getParam('default_thickness', 0);
			$materiale->rvalue = $this->_getParam('material_r_value', 0);
			$materiale->has_details = 0;
			if ($this->_getParam('material_conductivity') && $this->_getParam('material_capacity') && $this->_getParam('material_density')) {
				$materiale->has_details = 1;
			}
			$materiale->has_rvalue = $this->_getParam('has_rvalue', 0); // da implementare su form e ajax call
			$material->has_greenroof = 0;
			$materiale->has_ecarbon = 0;
			if ($this->_getParam('material_co2') == 1) {
				$materiale->has_ecarbon = 1;
			}
			$materiale->status = 1;
		
			$materiale->save();
			if ($scenario == "new") {
				$id_materiale = $materiali->getAdapter()->lastInsertId();
			} else {
				$id_materiale = $this->_getParam('id');
			}
		
			// proprietà fisiche
			$phy = new MaterialPropsPhysical();
			$phyProps = ($scenario == "new") ? $phy->createRow() : $phy->fetchRow($phy->select()->where('id = ?', $this->_getParam('id')));
		
			$phyProps->id = $id_materiale;
			$phyProps->thermal_absorptance = $this->_getParam('material_thermal_absorptance', 0);
			$phyProps->solar_absorptance = $this->_getParam('material_solar_absorptance', 0);
			$phyProps->visible_absorptance = $this->_getParam('material_visible_absorptance', 0);
			$phyProps->roughness = $this->_getParam('material_roughness', 0);
			$phyProps->save();
		
			// proprietà termiche
			$thermal = new MaterialPropsThermal();
			$thrmProps = ($scenario == "new") ? $thermal->createRow() : $thermal->fetchRow($thermal->select()->where('id = ?', $this->_getParam('id')));
		
			$thrmProps->id = $id_materiale;
			$thrmProps->conductivity = $this->_getParam('material_conductivity', 0);
			$thrmProps->capacity = $this->_getParam('material_capacity', 0);
			$thrmProps->density = $this->_getParam('material_density', 0);
			$thrmProps->save();
		
			// proprietà co2
			$ecarbon = new MaterialPropsEcarbon();
			$ecProps = ($scenario == "new") ? $ecarbon->createRow() : $ecarbon->fetchRow($ecarbon->select()->where('id = ?', $this->_getParam('id')));
		
			$ecProps->id = $id_materiale;
			$ecProps->co2 = $this->_getParam('material_co2', 0);
			$ecProps->conv_factor_name = $this->_getParam('material_conv_factor_name', '');
			$ecProps->source = $this->_getParam('material_ecarbon_source', '');
			$ecProps->assumption = $this->_getParam('material_assumption', '');
			$ecProps->co2e = $this->_getParam('material_co2e', 0);
			$ecProps->save();
		
			Model::getDefaultAdapter()->commit();
			if ($scenario == "new") {
				$msg = "Il materiale è stato aggiunto con successo al database";
			} else {
				$msg = "Le proprietà del materiale sono state aggiornate con successo";
			}
			$esito = true;
		
		} catch (Exception $ex) {
		
			$esito = false;
			Model::getDefaultAdapter()->rollBack();
			if ($scenario == "new") {
				echo $ex->getMessage();
				$msg = "Si è verificato un errore durante l'inserimento del nuovo materiale nel database";
			} else {
				$msg = "Si è verificato un errore durante l'aggiornamento delle proprietà del materiale nel database";
			}
		}
		
		$info = array ("esito" => $esito, "id" => $id_materiale, "messages" => $msg);
		return $info;
		*/
	}
}

function deep_urldecode($var) {
	if (is_array($var)) {
		foreach ($var as &$v) {
			deep_urldecode($v);
		}
	}
	else $var = urldecode($var);
	return $var;
}